<template>
	<el-row :gutter="15" class="myRow">
		<el-col :span="6">
			<div class="leftBox">
				<div class="toolBox">
					<el-button 
						icon="el-icon-plus" 
						type="primary"
						v-permission
						@click="groupIndexDialog.visible = true"
					>
						新增
					</el-button>
					<!-- <el-input
						class="searchGroupInput"
						prefix-icon="el-icon-search"
						v-model="groupIndex.filters.TITLE"
						placeholder="搜索组名..."
					></el-input> -->
					<el-button 
						icon="el-icon-delete" 
						type="danger"
						v-show="groupCardActivate != '0'"
						v-permission
						@click="handleClick('deleteGroup')"
					>
						删除
					</el-button>
				</div>
				<el-divider></el-divider>
				<div 
					class="groupIndexBox" 
					v-loading="groupIndex.loading"
					element-loading-text="拼命加载中"
					element-loading-spinner="el-icon-loading"
				>
					<el-card 
						class="groupCard"
						v-for="(item, index) in groupIndex.data" 
						:key="item.ID"
						:shadow="groupCardShadow(item.ID)" 
						:class="groupCardClass(item.ID)"
						@click.native="handleClick('groupCard', item.ID)"
						@mouseenter.native="handleMouseEnter('groupCard', item.ID)"
						@mouseleave.native="handleMouseLeave('groupCard', item.ID)"
					>
						<el-row :gutter="10">
							<el-col :span="15">
								<div>
									<span>{{ index + 1 }}</span>
									<el-divider direction="vertical"></el-divider>
									{{ item.TITLE }}
								</div>
							</el-col>
							<el-col :span="9">
								<div v-if="groupCardHover[item.ID] || item.ID == groupCardActivate">
									<!-- <el-button 
										icon="el-icon-edit" 
										type="text" 
										size="mini" 
										@click="handleClick('editGroupBtn', item)"
									>
										编辑组
									</el-button> -->
									<el-tag 
										:type="processGroupType(item.GROUP_TYPE).type"
										effect="plain"
										size="mini" 
									>
										{{ processGroupType(item.GROUP_TYPE).text }}
									</el-tag>
									<el-divider direction="vertical"></el-divider>
									<el-button 
										icon="el-icon-user-solid" 
										type="text" 
										size="mini" 
										v-permission
										@click="handleClick('memberManage', item)"
									>
										成员
									</el-button>
								</div>
							</el-col>
						</el-row>
					</el-card>
				</div>
			</div>
		</el-col>
		<el-col :span="18">
			<div class="rightBox">
				<!-- <div 
					v-loading="groupThreshold.loading"
					element-loading-text="拼命加载中"
					element-loading-spinner="el-icon-loading"
					v-for="item in groupThreshold.data" 
					:key="item.LID"
				>
					{{ item }}
				</div> -->
				<el-table
					v-loading="groupThreshold.loading"
					element-loading-text="拼命加载中"
					element-loading-spinner="el-icon-loading"
					:data="groupThreshold.data"
					:span-method="groupThresholdSpanMethod"
					style="width: 100%"
				>
					<el-table-column
						prop="OBJ_NAME"
						label="OBJ_NAME"
						width="200">
					</el-table-column>
					<el-table-column
						prop="DIS_NAME"
						label="名称"
						width="200">
					</el-table-column>
					<el-table-column
						prop="LEVEL_DISPLAY"
						label="告警级别"
						width="80">
						<template v-slot="scope">
							<div>
								<template v-if="scope.row['LEVEL_DISPLAY'] == '紧急'">
									<el-tag 
										type="danger" 
										size="mini" 
										effect="plain"
									>
										{{ scope.row['LEVEL_DISPLAY'] }}
									</el-tag>
								</template>
								<template v-else-if="scope.row['LEVEL_DISPLAY'] == '普通'">
									<el-tag 
										type="warning" 
										size="mini" 
										effect="plain"
									>
										{{ scope.row['LEVEL_DISPLAY'] }}
									</el-tag>
								</template>
                            </div>
						</template>
					</el-table-column>
					<el-table-column
						prop="ALERT_VALUE"
						label="警报值"
						width="150">
						<template v-slot="scope">
							<el-input-number 
								size="mini"
								v-model="scope.row.ALERT_VALUE" 
								v-permission
								:min="groupThreshold.valueRange[scope.row.OBJ_NAME][scope.row['LEVEL_VALUE']].min"
								:max="groupThreshold.valueRange[scope.row.OBJ_NAME][scope.row['LEVEL_VALUE']].max"
								@change="alertValueInputChange(scope.row)" 
								label="label">
							</el-input-number>
						</template>
					</el-table-column>
					<el-table-column
						prop="VALUEUNIT"
						label="单位"
						width="180">
					</el-table-column>
				</el-table>
			</div>
		</el-col>

		<!-- 弹窗：新增、编辑组 -->
		<el-dialog
			title=""
			:visible.sync="groupIndexDialog.visible"
			width="30%"
			@close="handleClose">
			<el-form :model="groupIndexDialog.form" label-width="80px">
				<el-form-item label="组名称">
					<el-input v-model="groupIndexDialog.form.groupName"></el-input>
				</el-form-item>
				<el-form-item label="组类别">
					<el-radio-group v-model="groupIndexDialog.form.groupType">
						<el-radio-button v-show="this.userType=='DataBase'||this.userType=='any'"  label="Database">数据库</el-radio-button>
						<el-radio-button  v-show="this.userType=='Server'||this.userType=='any'" label="Host">服务器</el-radio-button>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer">
				<el-button @click="groupIndexDialog.visible = false">取 消</el-button>
				<el-button type="primary" @click="handleClick('createNewGroup')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 弹窗：管理组成员 -->
		<el-dialog
			:title="groupMemberDialog.title"
			:visible.sync="groupMemberDialog.visible"
			center
			width="50%">
			<el-table
				ref="groupMemberTable"
				:data="groupMemberDialog.data"
				height="45%"
				style="width: 100%">
				<el-table-column
					type="index"
					width="50">
				</el-table-column>
				<el-table-column
					prop="IP"
					label="IP"
					width="150">
				</el-table-column>
				<el-table-column
					prop="SYSTEMNAME"
					label="SYSTEMNAME"
					width="">
				</el-table-column>
				<el-table-column
					prop="OBJECT"
					label="OBJECT"
					width="">
				</el-table-column>
			</el-table>
			<div slot="footer">
				<el-button @click="groupMemberDialog.visible = false">关闭</el-button>
			</div>
		</el-dialog>
	</el-row>
</template>

<script>
import { submitAdmin } from '@/api/index.js';
import { getUserData } from "@/utils/IndexedDB.js";
export default {
	name: 'mgThreshold',
	data() {
		return {
			postData: {
                opera: '',
                curPage: 1,
                pageSize: 10000,
                sort: {
                    sortColumn: '',
                    sortOrders: ''
                },
                filtersType: 'exactquery',	// 精确查询
				filters: {}
			},
			groupIndex: {
				get_opera: 'GetAlertGroupIndex',
				del_opera: 'DeleteAlertLevel',
				filters: {
					TITLE: ''
				},
				loading: false,
				data: []
			},
			groupThreshold: {
				get_opera: 'GetAlertLevelByGroup',
				edit_opera: 'modifyalertlevel',
				filters: {
					INDEX_ID: ''
				},
				loading: false,
				data: [],
				valueRange: {
					'objName': {
						'2': { min: 0, max: 1 },
						'3': { min: 1, max: 2 }
					}
				}
			},
			userType:'',
			groupCardActivate: '',
			groupCardHover: {},
			groupIndexDialog: {
				opera_Create: 'CreateAlertGroupIndex',
				visible: false,
				form: {
					opera: '',
					groupName: '',
					groupType: 'Database'	// Database、Host、All
				}
			},
			groupMemberDialog: {
				opera: 'GetAlertGroupMemberByGroup',
				filters: {
					INDEX_ID: ''
				},
				loading: false,
				data: [],
				title: '',
				visible: false,
			},
			
		};
	},
	created () {
		this.initData();
	},
	computed: {

	},
	methods: {
		async initData() {
			
                
             
			this.getGroupIndexData();
			// 选中默认组，并请求数据
			this.groupCardActivate = '0';
			this.groupThreshold.filters.INDEX_ID = '0';
			this.getGroupThresholdData();
			await getUserData("userBase", "infoBase", 0).then((res) => {
            //    this.userAuthority = res.userAuthority;
                
                if(res.ms_type=='superAdmin'||res.ms_type=='bigUser'||res.ms_type=='BSuser'||res.ms_type=='bigadmin'||res.ms_type=='BSadmin'){
					this.userType='any'
					
				}else if(res.ms_type=='Buser'||res.ms_type=='BNuser'||res.ms_type=='Badmin'||res.ms_type=='BNadmin'){
					this.userType='DataBase'
				}else if(res.ms_type=='Suser'||res.ms_type=='SNuser'||res.ms_type=='Sadmin'||res.ms_type=='SNadmin'){
					
					this.userType='Server'
				}else if(res.ms_type=='Nuser'||res.ms_type=='BNuser'||res.ms_type=='SNuser'||res.ms_type=='Nadmin'||res.ms_type=='BNadmin'||res.ms_type=='SNadmin'){
					this.userType='NetWork'
				}

				this.groupIndexDialog.form.groupType=(this.userType=='DataBase'||this.userType=='any')?'Database':(this.userType=='Server'?'Host':'')
				
            });
		},
		getGroupIndexData() {
			this.groupIndex.loading = true;

			this.postData.opera = this.groupIndex.get_opera;
			this.postData.filters = this.groupIndex.filters;
			submitAdmin({
                postData: JSON.stringify(this.postData)
            }).then((res) => {
				this.groupIndex.data = res.data;
				

                this.groupIndex.loading = false;
            });
		},
		getGroupMemberData() {
			this.groupMemberDialog.loading = true;

			this.postData.opera = this.groupMemberDialog.opera;
			this.postData.filters = this.groupMemberDialog.filters;
			submitAdmin({
                postData: JSON.stringify(this.postData)
            }).then((res) => {
				this.groupMemberDialog.data = res.data;

                this.groupMemberDialog.loading = false;
            });
		},
		getGroupThresholdData() {
			this.groupThreshold.loading = true;

			this.postData.opera = this.groupThreshold.get_opera;
			this.postData.filters = this.groupThreshold.filters;
			submitAdmin({
                postData: JSON.stringify(this.postData)
            }).then((res) => {
				this.groupThreshold.data = res.data;
				

				// 创建报警值范围，限制各等级的最大最小值
				let _valueRange = {};
				this.groupThreshold.data.filter((item) => {
					// obj key
					if (!_valueRange[item.OBJ_NAME]) {
						_valueRange[item.OBJ_NAME] = {};
					}

					// 添加二级 key
					if (item.LEVEL_VALUE == 3) {
						_valueRange[item.OBJ_NAME][2] = {
							min: 0,
							max: item.ALERT_VALUE
						};
					} else if (item.LEVEL_VALUE == 2) {
						_valueRange[item.OBJ_NAME][3] = {
							min: item.ALERT_VALUE,
							max: Infinity
						};
					}
				});
				this.$set(this.groupThreshold, 'valueRange', _valueRange);

                this.groupThreshold.loading = false;
            });
		},
		// 鼠标点击
		handleClick(flag, data) {
			let _this = this;
			let _run = {
				createNewGroup: function () {
					_this.groupIndexDialog.form.opera = _this.groupIndexDialog.opera_Create;
					_this.submitGroupData();
				},
				editGroupBtn: function () {
					_this.editGroupBtn();
				},
				memberManage: function () {
					_this.groupMemberDialog.visible = true;
					_this.groupMemberDialog.filters.INDEX_ID = data.ID;
					_this.groupMemberDialog.title = data.TITLE + ' 组内成员';
					_this.memberManage();
				},
				groupCard: function () {
					let _data = _this.groupThreshold.filters.INDEX_ID;

					_this.groupCardActivate = data;
					_this.groupThreshold.filters.INDEX_ID = data;
					if (_data != data) {
						_this.getGroupThresholdData();
					}
				},
				deleteGroup: function () {
					_this.submitDeleteGroup();
				}
			};
			// 执行匹配的函数
			_run[flag]();
		},
		// 鼠标移入
		handleMouseEnter(box, key) {
			if (this.groupCardHover.hasOwnProperty(key)) {
				this.groupCardHover[key] = true;
			} else {
				/**
				 * 对于已经创建的实例，Vue 不允许动态添加根级别的响应式 property。
				 * 可以用 set 添加响应式 property
				 */
				this.$set(this.groupCardHover, key, true)
			}
		},
		// 鼠标移出
		handleMouseLeave(box, item) {
			this.groupCardHover[item] = false;
		},
		submitGroupData() {
			let _data = this.groupIndexDialog.form;

			submitAdmin({
                postData: JSON.stringify(_data)
            }).then((res) => {
				if (res == '创建成功') {
					this.$message({
						message: '创建成功！',
						type: 'success'
					});
					
					this.getGroupIndexData();
					this.groupIndexDialog.visible = false;
				} else {
					this.$message({
						message: '创建失败，请检查填写是否正确！',
						type: 'error'
					});
				}
            });
		},
		editGroupBtn() {
			console.log('编辑组');
		},
		memberManage() {
			this.getGroupMemberData();
		},
		groupCardShadow(groupId) {
			if (groupId == this.groupCardActivate) {
				return 'always';
			} else {
				return 'hover'
			}
		},
		groupCardClass(groupId) {
			if (groupId == this.groupCardActivate) {
				return 'groupCardBG';
			} else {
				return ''
			}
		},
		processGroupType(groupType) {
			let _tagType = {
				ALL: 'danger',
				Database: 'primary',
				Host: 'success'
			};

			let _tagText = {
				ALL: '默认组',
				Database: '数据库',
				Host: '服务器'
			};

			return { type: _tagType[groupType], text: _tagText[groupType] };
		},
		handleClose() {
			this.groupIndexDialog.form = this.$options.data().groupIndexDialog.form;
		},
		submitDeleteGroup() {
			this.$confirm('此操作将永久删除选中组, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				if (this.groupCardActivate == '0') {
					this.$message({
						message: '非法操作，禁止删除默认组！',
						type: 'error'
					})
				} else {
					let _data = {
						opera: this.groupIndex.del_opera,
						id: this.groupCardActivate
					};
	
					submitAdmin({
						postData: JSON.stringify(_data)
					}).then((res) => {
						if (res == '删除成功') {
							this.$message({
								message: '删除成功！',
								type: 'success'
							});
							
							this.initData();
						} else {
							this.$message({
								message: '删除失败，请重试！',
								type: 'error'
							});
						}
					});
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		groupThresholdSpanMethod({ row, column, rowIndex, columnIndex }) {
			// console.log(column);
			if (column.property == 'OBJ_NAME' || column.property == 'DIS_NAME') {
				// console.log(row.LEVEL_VALUE);
				// if (row.LEVEL_VALUE == 2) {
				if (rowIndex % 2 == 0) {
					return {
						rowspan: 2,
						colspan: 1
					};
				} else {
					return {
						rowspan: 0,
						colspan: 0
					};
				}
			}
		},
		alertValueInputChange(row) {
			let _postData = {
				opera: this.groupThreshold.edit_opera,
				data: []
			};

			_postData.data.push(row);

			submitAdmin({
                postData: JSON.stringify(_postData)
            }).then((res) => {
				if (res == '修改成功') {
					this.$message({
						message: '修改成功！',
						type: 'success',
						duration: 1000
					});

					this.getGroupThresholdData();
				} else {
					this.$message({
						message: res,
						type: 'error'
					});
				}
            });
		}
	}
};
</script>

<style scoped>
.myRow,
.myRow > .el-col,
.myRow > .el-col > div {
	/* height: 100%; */
	/* height: 85vh; */
}
.myRow > .el-col > div {
	padding: 15px;
	border-radius: 4px;
	background: #fff;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* 工具栏 */
.myRow > .el-col > div.leftBox .toolBox {
	display: inline-block;
}
.myRow > .el-col > div.leftBox .toolBox button:first-child {
	margin-right: 15px;
}
.myRow > .el-col > div.leftBox .toolBox .searchGroupInput {
	width: 200px;
	margin-right: 15px;
}
/* 阈值组 */
.myRow > .el-col > div.leftBox > .groupIndexBox > .groupCard {
	margin-bottom: 10px;
}
.myRow > .el-col > div.leftBox .groupIndexBox > .groupCard > .el-card__body {
	padding: 10px 15px;
}
.myRow > .el-col > div.leftBox .groupIndexBox > .groupCard > .el-card__body > .el-row > .el-col {
	line-height: 32px;
}
.myRow > .el-col > div.leftBox > .groupIndexBox > .groupCard > .el-card__body > .el-row > .el-col .el-button--text {
	color: darkcyan;
}
.myRow > .el-col > div.leftBox > .groupIndexBox > .groupCard > .el-card__body > .el-row > .el-col .el-button--text:hover {
	color: cadetblue;
}
.myRow > .el-col > div.leftBox > .groupIndexBox > .groupCard > .el-card__body > .el-row > .el-col:last-child {
	text-align: right;
}
.myRow > .el-col > div.leftBox > .groupIndexBox > .groupCardBG {
	color: currentColor;
	background: antiquewhite;
}
</style>
